package com.ym.core.domain;

import com.github.pagehelper.PageInfo;
import com.ym.common.constant.Coder;
import com.ym.common.utils.ServletUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

public abstract class BaseController {


	public static Session getSession() {
		return SecurityUtils.getSubject().getSession();
	}


	/**
	 * 返回成功
	 */
	public APIResponse<Void> success() {
		return APIResponse.success();
	}

	/**
	 * 返回成功
	 */
	public <T> APIResponse<T> successData(T data) {
		return APIResponse.success(data);
	}

	/**
	 * 响应请求分页数据
	 */
	protected <T> APIResponse<PageInfo<T>> successPage(List<T> list) {
		return APIResponse.success(new PageInfo<T>(list));
	}

	/**
	 * 返回成功
	 */
	public APIResponse successMsg(String msg) {
		return APIResponse.success(msg, null);
	}


	/**
	 * 返回失败
	 */
	public APIResponse fail() {
		return APIResponse.fail();
	}

	/**
	 * 返回失败
	 */
	public APIResponse failCode(Coder code) {
		return APIResponse.fail(code);
	}

	/**
	 * 返回失败
	 */
	public APIResponse failMsg(String msg) {
		return APIResponse.fail(msg);
	}

	/**
	 * 页面跳转
	 */
	public String redirect(String url) {
		return String.format("redirect:%s", url);
	}

	/**
	 * 下载
	 */
	public void setDownloadResponse(String fileName) {
		HttpServletResponse response = ServletUtil.getResponse();
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-disposition",
				"attachment; filename=" + ServletUtil.setFileDownloadHeader(fileName));
		response.setContentType("application/x-msdownload");
	}

	/**
	 * 下载
	 */
	public APIResponse download(String fileName, HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-disposition",
				"attachment; filename=" + fileName);
		response.setContentType("application/x-msdownload");
		return success();
	}
}
